package cn.com.dhcc.turbo.web.controller.monitor;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.modulehandler.valuebean.BetweenValue;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.DTUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.turbo.entity.exch.CarvedDiscsUpload;
import cn.com.dhcc.turbo.entity.exch.CarvedDiscsUploadData;
import cn.com.dhcc.turbo.service.exch.cmdata.CarvedDiscsUploadDataService;
import cn.com.dhcc.turbo.service.exch.cmdata.CarvedDiscsUploadService;


/**
 * 刻盘管理Controller
 * 
 * @日期 2014-10-14 下午2:34:28
 * @作者  高强
 */
@Controller
@RequestMapping("/monitor")
@TurboMenu(belongToMenu=LEAF_MENU.CARVED_DISCS_MANAGE)
public class CarvedDiscsUploadController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);

	@Autowired
	private CarvedDiscsUploadService carvedDiscsUploadService;
	@Autowired
	private CarvedDiscsUploadDataService carvedDiscsUploadDataService;
	
	@RequestMapping(value = "/carved_discs_upload_list")
	public String list(
			Model model, 
			Pager pager, 
			String sendBusicode, 
			String batchId,
			String startCreated, 
			String endCreated, 
			String orderName, 
			String order) {
		try {
			WhereCondition searchData = new WhereCondition();
			searchData.where().notEq("id", "0");
			
			if (StrUtil.isNotBlank(sendBusicode)) {
				searchData.and().like("send_busicode", sendBusicode);
			}
			
			if (StrUtil.isNotBlank(batchId)) {
				searchData.and().like("batch_id", batchId);
			}
			
			//这里对发生中的状态进行了处理，把本地发送和远程发送都看做为发送中
			/*if (StrUtil.isNotBlank(sendStatus)) {
				if (AppConst.SendStatus.LOCAL_SENDING.value().equals(sendStatus)) {
					searchData.and().leftBracket()
								.eq("send_status", sendStatus)
								.or()
								.eq("send_status", AppConst.SendStatus.REMOTE_SENDING.value())
								.rightBracket();
				} else {
					searchData.and().eq("send_status", sendStatus);
				}
			}*/
			//时间范围从那天到那天
			if (StrUtil.isNotBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {
				searchData.and().between("uploadDate", new BetweenValue(DTUtil.toDateTime(startCreated) , DTUtil.toDateTime(endCreated)));
			}

			//时间范围，大于等于某天
			if (StrUtil.isNotBlank(startCreated) && StrUtil.isBlank(endCreated)) {	
				searchData.and().between("uploadDate", new BetweenValue(DTUtil.toDateTime(startCreated), null, true, false));
			}

			//时间范围，小于等于某天
			if (StrUtil.isBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {	
				searchData.and().between("uploadDate", new BetweenValue(null, DTUtil.toDateTime(endCreated), false, true));
			}
			
			if (StrUtil.isNotBlank(orderName)) {
				searchData.orderBy(orderName + " " + order);
			} else {
				searchData.orderBy("uploadDate  desc");
			}
			PagerData<CarvedDiscsUpload> datas = carvedDiscsUploadService.getPagerList(pager, searchData);
			List<CarvedDiscsUpload> dataList = datas.getDatas();
			List<CarvedDiscsUpload> dataListNew =new ArrayList<CarvedDiscsUpload>();
			if (dataList!=null && !dataList.isEmpty()) {
				for (CarvedDiscsUpload carvedDiscsUpload : dataList) {
					if (carvedDiscsUpload.getAnalyzeStatus().equals(AppConst.AnalyzeStatus.ANALYZE_SUCCESS.value())) {//如果解析成功的
						String status=carvedDiscsUploadDataService.getStatus(carvedDiscsUpload.getOrderId());
						carvedDiscsUpload.setProcessStatus(status);
					}
					dataListNew.add(carvedDiscsUpload);
				}
			}
			datas.setDatas(dataListNew);
			model.addAttribute(DATA_KEY, dataListNew);
			setTotoal(model, datas.getTotal());
			return "monitor/carved_discs_upload_list";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}
	
	@RequestMapping(value = "/carved_discs_upload_file", method = RequestMethod.POST)  
    @ResponseBody  
    public String uploadFile(HttpServletResponse response,HttpServletRequest request,@RequestParam(value="file", required=false) MultipartFile[] file){  
//		String responseStr="";  
		for (MultipartFile f : file) {
//            System.out.println(f.getOriginalFilename());  
            File dirPath = new File(AppConst.APP_CD_UPLOAD);  
            if (!dirPath.exists()) {  
                dirPath.mkdirs();  
            }  
            File uploadedFile = new File(dirPath, f.getOriginalFilename());  
            CarvedDiscsUpload upload=new CarvedDiscsUpload();
            upload.setId(UUIDGenerator.getUUID());
            upload.setCarvedName(uploadedFile.getName());
            upload.setAnalyzeStatus("0");
            upload.setProcessStatus("0");
            upload.setUploadDate(new Date());
            upload.setFilesize(f.getSize());
            try {  
            	carvedDiscsUploadService.insert(upload);
                FileCopyUtils.copy(f.getBytes(), uploadedFile);    
                return jsonSuccessResult("上传成功").toString();
            } catch (IOException e) {  
               return jsonFailResult("上传失败"+e).toString();
            } catch (ServiceException e) {
            	return jsonFailResult("上传失败"+e).toString();
			}    
		  }
		return null;
    } 
	@RequestMapping(value = "/carved_discs_upload_get/{id}")
	public String get(@PathVariable String id,Model model,Pager pager){
			try {
				CarvedDiscsUpload vo = carvedDiscsUploadService.get(id);
				String status=carvedDiscsUploadDataService.getStatus(vo.getOrderId());
				vo.setProcessStatus(status);
				WhereCondition searchData = new WhereCondition();
				searchData.where().in("id", vo.getOrderId().split(","));
				PagerData<CarvedDiscsUploadData> datas = carvedDiscsUploadDataService.getPagerList(pager, searchData);
			    List<CarvedDiscsUploadData> dataList = datas.getDatas();
			    model.addAttribute(DATA_KEY, dataList);
			    model.addAttribute(VO_KEY, vo);
			    setTotoal(model, datas.getTotal());
				return "monitor/carved_discs_upload_get";
			} catch (Exception e) {
				logger.error("操作失败", e);
				return toAlertPage(model, e.getMessage());
			} 
	}
	
	
}
